package com.stu.wgt.test.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.stu.wgt.test.bean.ProductCategories;
import com.stu.wgt.test.result.R;
import com.stu.wgt.test.service.ProductCategoriesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author wgt
 * @since 2024-02-04
 */
@RestController
@RequestMapping("/product-categories")
public class ProductCategoriesController {
    @Autowired
    ProductCategoriesService productCategoriesService;

    @GetMapping("/selectProduct")
    public R selectAll(@RequestParam(required = false) Integer type,
                       @RequestParam(value = "pagenum", defaultValue = "1") int pageNum,
                       @RequestParam(value = "pagesize", defaultValue = "10") int pageSize) {
        IPage<ProductCategories> prolist = productCategoriesService.searchProductCategories(type, pageNum, pageSize);
        return R.ok().data("prolist", prolist.getRecords()).data("total", prolist.getTotal());
    }

    @GetMapping("/selectById/{id}")
    public R selectById(@PathVariable("id") Integer id) {
        System.out.println(id);
        try {
            List<ProductCategories> list = productCategoriesService.selectById(id);
            return R.ok().data("prolist", list);
        } catch (Exception e) {
            return R.error().data("msg", "查无此人,请提供正确的ID");
        }
    }

    // 根据分类等级获取数据
    @PostMapping("/add")
    public R add(@RequestBody ProductCategories productCategories) {
        System.out.println(productCategories);

        int result = productCategoriesService.insert(productCategories);
        if (result == 1) {
            return R.ok().data("msg", "添加成功");
        } else {
            return R.error().data("msg", "添加失败,分类名称已存在");
        }
    }

    // 根据ID删除分类
    @DeleteMapping("/delete/{id}")
    public R delete(@PathVariable("id") Integer id) {
        System.out.println(id);
        int result = productCategoriesService.delete(id);
        if (result == 1) {
            return R.ok().data("msg", "删除成功");
        } else {
            return R.error().data("msg", "不存在该用户删除失败");
        }
    }

    // 根据id修改分类
    @PutMapping("/update/{id}")
    public R update(@RequestBody ProductCategories productCategories, @PathVariable("id") Integer id) {
        System.out.println(productCategories);
        productCategories.setId(id);
        int result = productCategoriesService.update(productCategories);
        if (result == 1) {
            return R.ok().data("msg", "更新成功");
        } else {
            return R.error().data("msg", "更新失败");
        }
    }
}

